<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页</title>
</head>
<body>
<!-- 
    分页思想：
        1. 假如有 101 条数据，每页展示 10 条，页数有 101/10 = 11 页
        2. 每页初始下标：（当前页-1） * 每页条数，从初始下标开始遍历;
           每页结束下标： 当前页 * 每页条数，不包含这一条，结束下标最大为总条数。

 -->

<p>第 <span class="page"></span> 页数据</p>
<ul class="data"></ul>

</body>

<script>

    // 以下纯手写

    let arrOrigin = Array.from(new Array(101), (v, i) => i + 1)
    console.log('101条数据', arrOrigin)    

    let curData = []
    let curPage = 1 // 当前页
    let pageSize = 10 //每页条数
    let total = arrOrigin.length // 总条数
    
    // 渲染页数按钮
    function setPageBtn(){
        let pageNum = Math.ceil(total / pageSize) // 总页数
        for(let i = 1; i <= pageNum; i++){
            let btn = document.createElement('button')
            btn.innerText = i
            btn.addEventListener('click', ()=>changeCurPage(i))
            document.body.appendChild(btn)
        }
    }
    setPageBtn()

    function changeCurPage(page){
        console.log('changeCurPage',page)
        curPage = page
        let pageEle = document.querySelector('.page')
        pageEle.innerText = curPage

        let startIndex = (curPage - 1) * pageSize
        let endIndex = (curPage * pageSize) > total ? total : curPage * pageSize

        curData = []
        document.querySelector('.data').innerHTML = ''
        for(let i = startIndex; i < endIndex; i++){
            curData.push(arrOrigin[i])
            let li = document.createElement('li')
            li.innerText = arrOrigin[i]
            document.querySelector('.data').appendChild(li)
        }
        console.log('curData', curData)
    }
    changeCurPage(curPage)


</script>
</html>